import sys

from PyQt6.QtCore import QThread, pyqtSignal, QDateTime
from PyQt6.QtWidgets import QWidget, QListWidget, QPushButton, QVBoxLayout, QGridLayout, QApplication


class Worker(QThread):
    # 接收者 Worket
    signal = pyqtSignal(str)

    def __init__(self, parent=None):
        super(Worker, self).__init__(parent)
        self.working = True

    def run(self):
        while self.working:
            time = QDateTime.currentDateTime()
            timeStr = time.toString("yyyy-MM-dd hh:mm:ss")
            # 触发信号
            self.signal.emit(timeStr)
            self.sleep(1)


class widget_thread(QWidget):
    def __init__(self, parent=None):
        super(widget_thread, self).__init__(parent)
        self.setWindowTitle("QThread 线程测试")
        self.list = QListWidget(self)
        self.button = QPushButton('start', self)
        layout = QGridLayout()
        layout.addWidget(self.list, 0, 0, 1, 2)
        layout.addWidget(self.button, 1, 1)
        self.button.clicked.connect(self.startThread)
        self.thread = Worker()
        # 连接处理信号
        self.thread.signal.connect(self.listAdd)

    def listAdd(self, strInf):
        self.list.addItem(strInf)

    def startThread(self):
        self.button.setEnabled(False)
        self.thread.start()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = widget_thread()
    w.show()
    sys.exit(app.exec())

